package com.lvmama.rhino.web;

import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.pojo.PriceDetail;
import com.lvmama.rhino.pojo.PriceDetailQuery;
import com.lvmama.rhino.pojo.StockDetail;
import com.lvmama.rhino.pojo.StockDetailQuery;
import com.lvmama.rhino.pojo.base.BaseResponseVO;
import com.lvmama.rhino.service.PriceService;
import com.lvmama.rhino.utils.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("price")
public class PriceController {
    @Autowired
    private PriceService priceService;

    
    private Logger log = Logger.getLogger(PriceController.class);

    @RequestMapping("detail")
    public String detail(ModelMap model) {
        try {
            //生成日期
            String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
            List<String> days = new ArrayList<>();
            for (String day : latestDays) {
                days.add(day.substring(5, 10));
            }
            String day = JSONConversionUtil.objToString(days);
            model.addAttribute("days", day);
            model.addAttribute("currentDays", days);
        } catch (Exception e) {
            log.error("detail error:{}" + e.getMessage(), e);
        }
        return "application/price/priceDetail";
    }
    
    
    @RequestMapping("detailSearch")
    @ResponseBody
    public BaseResponseVO<String> detailSearch(@RequestBody PriceDetailQuery query ) {
        //查询库存详情
        return getPriceNumByQuery(query);
    }
    
    /**
	 * 价格明细图表数据处理
	 * @param query
	 * @return
	 */
    private BaseResponseVO<String> getPriceNumByQuery(PriceDetailQuery query){
		PriceDetail priceDetail = priceService.selectPriceDetail(query).get(0);
        return getPriceNumList(priceDetail);
    }

	/**
	 * 导出汇总excel
	 * @param query
	 * @return
	 */
	@RequestMapping("exportPriceGather")
	public void exportPriceGather( PriceDetailQuery query, HttpServletResponse response){

		List<PriceDetail> list = null;
		//如果是大区先取分页中的数据
		if (query.getGroupByRegionname()){
			PageInfoUtil<PriceDetail> page = this.priceService.selectPriceGatherPageByRedis(query, 100);
			list = page.getList();
		}else {
			list = this.priceService.selectPriceGather(query);
		}
		//如果是大区先取分页中的数据
		exportExcel(query, response, list, false);
	}

	/**
	 * 导出明细excel
	 * @param query
	 * @return
	 */
	@RequestMapping("exportPriceDetail")
	public void exportPriceDetail( PriceDetailQuery query, HttpServletResponse response){
		//如果是大区先取分页中的数据
		List<PriceDetail> list = this.priceService.selectPriceDetail(query);
		exportExcel(query, response, list, true);
	}

	/**
	 * 导出excel方法
	 * @param query
	 * @param response
	 * @param list
	 * @param isDetail
	 */
	private void exportExcel(PriceDetailQuery query, HttpServletResponse response, List<PriceDetail> list, boolean isDetail){
		//导出excel文件
		ExportExcelUtils ex = new ExportExcelUtils();
		String title = getExcelTitle(query);
		//生成日期
		String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
		String[] headers = new String[latestDays.length + 1];
		headers[0] = title;
		int j = 1;
		//生成excel头列表
		for (String day : latestDays){
			headers[j++] = day;
		}
		OutputStream fOut = null;
		try {
			// 生成提示信息，
			response.setContentType("application/vnd.ms-excel");
			// 是否是明细
			if (isDetail){
				title = "价格明细-" + title;
			}else{
				title = "价格汇总-" + title;
			}
			// 进行转码，使其支持中文文件名
			String codedFileName = java.net.URLEncoder.encode( title + "统计文档", "UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
			fOut = response.getOutputStream();
			Field[] fields = getFields(headers, query);
			ex.exportExcel(title, headers, fields, list, fOut, "yyyy-MM-dd");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getExcelTitle(PriceDetailQuery query){
		String title = "";
		if (query.getGroupByBranch()){
			title = "房型";
		}else  if(query.getGroupByCategory()){
			title = "品类";
		}else  if(query.getGroupByChannel()){
			title = "渠道";
		}else  if(query.getGroupByRegionname()){
			title = "大区";
		}else  if(query.getGroupByHotle()){
			title = "酒店";
		}
		return title;

	}
	/**
	 * 根据每列字段名称创建需要导出字段的数组
	 *
	 * @param headers
	 * @param query
	 * @return
	 */
	private Field[] getFields(String[] headers, PriceDetailQuery query) {
		Field[] fields = new Field[headers.length];
		//获取对象所有的属性值放到集合中
		PriceDetail t = new PriceDetail();
		Field[] fieldList = t.getClass().getDeclaredFields();
		try {
			if (query.getGroupByBranch()){
				fields[0] = t.getClass().getDeclaredField("branchName");
			}else  if(query.getGroupByCategory()){
				fields[0] = t.getClass().getDeclaredField("categoryName");
			}else  if(query.getGroupByChannel()){
				fields[0] = t.getClass().getDeclaredField("saleChannel");
			}else  if(query.getGroupByRegionname()){
				fields[0] = t.getClass().getDeclaredField("regionname");
			}else  if(query.getGroupByHotle()){
				fields[0] = t.getClass().getDeclaredField("productName");
			}
			int i = 1;
			for (Field field : fieldList) {
				String fieldName = field.getName();
				if(fieldName.startsWith("price") && !fieldName.equals("price1")){
					fields[i] = field;
					i ++;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return fields;
	}
    /**
	 * 价格数据处理
	 * @return
	 */
    private BaseResponseVO<String> getPriceNumList(PriceDetail priceDetail){
    	BaseResponseVO<String> responseVo = new BaseResponseVO<String>();
    	responseVo.setCode(1);
    	if (priceDetail == null){
    		responseVo.setCode(0);
    		responseVo.setMessage("数据不存在");
    		return responseVo;
    	}
    	try {
    		 //获取对象所有的属性值放到集合中
    		 Field[] fields = priceDetail.getClass().getDeclaredFields();
    		 if (fields == null || fields.length == 0){
    			responseVo.setCode(0);
             	responseVo.setMessage("服务异常");
 				return responseVo;
    		 }
             List<String> priceNums = new ArrayList<>();
             for (Field field : fields) {
                 field.setAccessible(true);
                 String fieldName = field.getName();
                 if(fieldName.startsWith("price") && !fieldName.equals("price1")){
                     String  priceNum = (String) field.get(priceDetail);
                     priceNums.add(priceNum);
				 }else if (fieldName.equals("parDay")){
					 responseVo.setMessage((String)field.get(priceDetail));
				 }
             }
             responseVo.setDataList(priceNums);
             return responseVo;
		} catch (IllegalAccessException e) {
			log.error("detail error:{}" + e.getMessage(), e);
		}
    	responseVo.setCode(0);
     	responseVo.setMessage("服务异常");
		return responseVo;
    }
    /**
     * 各类明细查询不含分页
     * @param query
     * @return
     */
    @RequestMapping("detailSearchNoPage")
    @ResponseBody
    public BaseResponseVO<PriceDetail> detailSearchNoPage(@RequestBody PriceDetailQuery query){
    	BaseResponseVO<PriceDetail> responseVo = new BaseResponseVO<PriceDetail>();
    	List<PriceDetail> list = this.priceService.selectPriceDetail(query);
    	if (list == null || list.size() == 0){
			responseVo.setCode(0);
			responseVo.setMessage("数据不存在");
			return responseVo;
		}
		responseVo.setCode(1);
		responseVo.setDataList(list);
		return responseVo;
		
    }
    
    /**
     * 酒店明细分页查询
     * @param query
     * @return
     */
    @RequestMapping("hotelSearchPage")
    @ResponseBody
    public BaseResponseVO<PriceDetail> hotelSearchPage(@RequestBody PriceDetailQuery query){
    	BaseResponseVO<PriceDetail> responseVo = new BaseResponseVO<PriceDetail>();
    	try {
    		PageInfo<PriceDetail> page = this.priceService.selectPriceDetailPage(query);
    		if (page == null || page.getList() == null || page.getList().size() == 0){
    			responseVo.setCode(0);
    			responseVo.setMessage("数据不存在");
    			return responseVo;
    		}
    		responseVo.setCode(1);
    		responseVo.setPageInfo(page);
    		return responseVo;
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	
    	responseVo.setCode(0);
		responseVo.setMessage("服务异常");
		return responseVo;
    }
    
    /**
     * 房型明细分页查询
     * @param query
     * @return
     */
    @RequestMapping("branchSearchPage")
    @ResponseBody
    public BaseResponseVO<PriceDetail> branchSearchPage(@RequestBody PriceDetailQuery query){
    	BaseResponseVO<PriceDetail> responseVo = new BaseResponseVO<PriceDetail>();
    	try {
    		PageInfo<PriceDetail> page = this.priceService.selectAllPriceDetailPage(query);
    		if (page == null || page.getList() == null || page.getList().size() == 0){
    			responseVo.setCode(0);
    			responseVo.setMessage("数据不存在");
    			return responseVo;
    		}
    		responseVo.setCode(1);
    		responseVo.setPageInfo(page);
    		return responseVo;
    		
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	
    	responseVo.setCode(0);
		responseVo.setMessage("服务异常");
		return responseVo;
    }
    
    
    @RequestMapping("priceGather")
    public String priceGather(ModelMap model) {
    	try {
    		//生成日期
    		String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
    		List<String> days = new ArrayList<>();
    		for (String day : latestDays) {
    			days.add(day.substring(5, 10));
    		}
    		String day = JSONConversionUtil.objToString(days);
    		model.addAttribute("days", day);
    		model.addAttribute("currentDays", days);
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	return "application/price/priceGather";
    }

    
    @RequestMapping("gatherSearch")
    @ResponseBody
    public BaseResponseVO<String> gatherSearch(@RequestBody PriceDetailQuery query ) {
    	//查询价格详情
    	return getPriceGatherNumByQuery(query);
    }

    /**
     * 大区汇总分页查询
     * @param query
     * @return
     */
    @RequestMapping("regionSearchPage")
    @ResponseBody
    public BaseResponseVO<PriceDetail> regionSearchPage(@RequestBody PriceDetailQuery query){
        BaseResponseVO<PriceDetail> responseVo = new BaseResponseVO<PriceDetail>();
        try {
            PageInfoUtil<PriceDetail> page = this.priceService.selectPriceGatherPageByRedis(query, 10);
            if (page == null || page.getList() == null || page.getList().size() == 0){
                responseVo.setCode(0);
                responseVo.setMessage("数据不存在");
                return responseVo;
            }
            responseVo.setCode(1);
            responseVo.setPage(page);
            return responseVo;

        } catch (Exception e) {
            log.error("detail error:{}" + e.getMessage(), e);
        }

        responseVo.setCode(0);
        responseVo.setMessage("服务异常");
        return responseVo;
    }

    /**
     * 各类汇总查询
     * @param query
     * @return
     */
    @RequestMapping("gatherDetailSearch")
    @ResponseBody
    public BaseResponseVO<PriceDetail> gatherDetailSearch(@RequestBody PriceDetailQuery query ) {
    	//查询价格详情
    	BaseResponseVO<PriceDetail> responseVo = new BaseResponseVO<PriceDetail>();
    	List<PriceDetail> list = this.priceService.selectPriceGather(query);
    	if (list == null || list.size() == 0){
			responseVo.setCode(0);
			responseVo.setMessage("数据不存在");
			return responseVo;
		}
		responseVo.setCode(1);
		responseVo.setDataList(list);
		return responseVo;
    }
    
	/**
	 * 价格汇总图表数据处理
	 * @param query
	 * @return
	 */
    private BaseResponseVO<String> getPriceGatherNumByQuery(PriceDetailQuery query){
		PriceDetail priceDetail = priceService.selectPriceGather(query).get(0);
		return getPriceNumList(priceDetail);
    }
    

}
